package com.cms.controllers;

import java.text.DateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.cms.entity.Action;
import com.cms.entity.Role;
import com.cms.service.ActionService;
import com.cms.service.RoleService;
import com.cms.support.Result;

/**
 * @ClassName: RoleController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author zhangp
 * @date 2016年3月31日 下午2:41:25
 * 
 */
@Controller
public class RoleController {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(RoleController.class);
	@Autowired
	private RoleService roleService;
	@Autowired
	private ActionService actionService;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class,
				new CustomDateEditor(DateFormat.getDateTimeInstance(), true));
	}

	@ModelAttribute
	public void loadActions(Model model) {
		model.addAttribute("action_root",
				actionService.getActionByRoles(Collections.<Role> emptySet()));
	}

	@RequestMapping("/role")
	public String index(Model model) {
		return "role/index";
	}

	/**
	 * @Title: list
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param authority
	 * @param description
	 * @param iDisplayLength
	 * @param iDisplayStart
	 * @param sEcho
	 * @param model
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "role/list")
	public Object list(String authority, String description,
			Integer iDisplayLength, Integer iDisplayStart, Integer sEcho,
			Model model) {
		try {
			// 减去的是role_admin该角色不能操作
			Long totalCount = roleService.getCount(authority, description) - 1;
			List<Role> list = roleService.listDateRoles(authority, description,
					iDisplayStart, iDisplayLength);
			JSONObject getObj = new JSONObject();
			getObj.put("sEcho", sEcho);// 不知道这个值有什么用,有知道的请告知一下
			getObj.put("iTotalRecords", totalCount);// 实际的行数
			getObj.put("iTotalDisplayRecords", totalCount);// 显示的行数,这个要和上面写的一样
			getObj.put("aaData", list);// 要以JSON格式返回
			return getObj;
		} catch (Exception e) {
			LOGGER.error("查询角色失败:", e);
			return null;
		}
	}

	/**
	 * @Title: add
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "role/add", method = RequestMethod.GET)
	public String add(Model model) {
		Role role = new Role();
		role.setAuthority("ROLE_");
		model.addAttribute("role", role);
		return "role/add";
	}

	/**
	 * @Title: add
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param role
	 * @param actionIds
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "role/add", method = RequestMethod.POST)
	public Object add(Model model, Role role, int[] actionIds) {
		try {
			Role rol = roleService.queryRoleByAuthority(role.getAuthority());
			if (rol != null) {
				return new Result(false, "保存失败，已经存在相同角色名字！");
			}
			Set<Action> actions = new HashSet<Action>();
			for (int i = 0; i < actionIds.length; i++) {
				Action action = new Action();
				action.setId(actionIds[i]);
				actions.add(action);
			}
			List<Action> allActions = actionService.listActions();
			Set<Action> pActions = new HashSet<Action>();
			// 添加勾选项的父节点
			for (Action action : allActions) {
				if (action.getChildren() != null
						&& action.getChildren().size() > 0
						&& action.getUrl() != null
						&& action.getUrl().split("/").length > 1) {
					System.out.println();
					for (Action action2 : action.getChildren()) {
						for (int i = 0; i < actionIds.length; i++) {
							if (actionIds[i] == action2.getId()) {
								pActions.add(action);
							}
						}
					}

				}
			}
			// 添加根节点
			Action ac = new Action();
			ac.setId(1);
			actions.add(ac);
			actions.addAll(pActions);
			role.setActions(actions);
			roleService.saveRole(role);
			return new Result();
		} catch (Exception e) {
			LOGGER.error("添加角色失败:", e);
			return new Result(false, "系统异常");
		}
	}

	/**
	 * @Title: modify
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param id
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "role/modify", method = RequestMethod.GET)
	public String modify(Model model, @RequestParam Integer id) {
		Role role = roleService.getRole(id);
		model.addAttribute("role", role);
		return "role/modify";
	}

	/**
	 * @Title: modify
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param role
	 * @param actionIds
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "role/modify", method = RequestMethod.POST)
	public Object modify(Model model, Role role, int[] actionIds) {
		try {
			Set<Action> actions = new HashSet<Action>();
			for (int i = 0; i < actionIds.length; i++) {
				Action action = new Action();
				action.setId(actionIds[i]);
				actions.add(action);
			}
			List<Action> allActions = actionService.listActions();
			Set<Action> pActions = new HashSet<Action>();
			for (Action action : allActions) {
				if (action.getChildren() != null
						&& action.getChildren().size() > 0
						&& action.getUrl() != null
						&& action.getUrl().split("/").length > 1) {
					for (Action action2 : action.getChildren()) {
						for (int i = 0; i < actionIds.length; i++) {
							if (actionIds[i] == action2.getId()) {
								pActions.add(action);
							}
						}
					}
				}
			}
			Action ac = new Action();
			ac.setId(1);
			actions.add(ac);
			actions.addAll(pActions);
			role.setActions(actions);
			role.setCreateDate(new Date());
			roleService.update(role);
			return new Result();
		} catch (Exception e) {
			LOGGER.error("修改角色错误：", e);
			return new Result(false, "系统异常");
		}

	}

	/**
	 * @Title: delete
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param id
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "role/delete", method = RequestMethod.POST)
	public Object delete(@RequestParam Integer id) {
		try {
			roleService.removeById(id);
			return new Result();
		} catch (Exception e) {
			LOGGER.error("role/delete 删除角色错误：", e);
			return new Result(false, "角色存在关联操作员，删除失败!");
		}
	}

}
